﻿namespace S4sme.Core.Extensions
{
    using System.Globalization;
    using System.Text;
    using System.Text.RegularExpressions;

    /// <summary>
    /// String extensions
    /// </summary>
    public static class StringExtensions
    {
        public static string GenerateSlug(this string text)
        {
            text = RemoveAccent(text).ToLower();

            text = Regex.Replace(text, @"[^a-z0-9\s-]", string.Empty); // invalid chars           
            text = Regex.Replace(text, @"\s+", " ").Trim(); // convert multiple spaces into one space   
            text = text.Substring(0, text.Length <= 200 ? text.Length : 200).Trim(); // cut and trim it   
            text = Regex.Replace(text, @"\s", "-"); // hyphens   

            return text;
        }

        /// <summary>
        /// Gets the Tag Class based on the count of posts
        /// </summary>
        /// <see>Thanks to Mike Brind http://www.mikesdotnetting.com/Article/107/Creating-a-Tag-Cloud-using-ASP.NET-MVC-and-the-Entity-Framework</see>
        /// <param name="postsInTag">Number of posts for a specific tag</param>
        /// <param name="totalPosts">Total number of posts in the system</param>
        /// <returns>css class string</returns>
        public static string GetTagClass(int postsInTag, int totalPosts)
        {
            var result = (postsInTag * 100) / totalPosts;
            if (result <= 1)
            {
                return "tag1";
            }

            if (result <= 4)
            {
                return "tag2";
            }

            if (result <= 8)
            {
                return "tag3";
            }

            if (result <= 12)
            {
                return "tag4";
            }

            if (result <= 18)
            {
                return "tag5";
            }

            if (result <= 30)
            {
                return "tag6";
            }

            return result <= 50 ? "tag7" : string.Empty;
        }

        public static string CorrectedLongDatePattern(CultureInfo cultureInfo)
        {
            var info = cultureInfo.DateTimeFormat;

            // This is bad, mmmkay?
            return Regex.Replace(info.LongDatePattern, "dddd,?", string.Empty).Trim();
        }

        private static string RemoveAccent(string txt)
        {
            byte[] bytes = Encoding.GetEncoding("Cyrillic").GetBytes(txt);
            return Encoding.ASCII.GetString(bytes);
        }
    }
}